package cn.lili.modules.payment.kit.plugin.wallet;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.GradeLevel;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.vo.GradeVO;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.GradeLevelMapper;
import cn.lili.modules.member.mapper.GradeMapper;
import cn.lili.modules.member.mapper.MemberMapper;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.vo.OrderVO;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.payment.entity.RefundLog;
import cn.lili.modules.payment.entity.enums.CashierEnum;
import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
import cn.lili.modules.payment.kit.CashierSupport;
import cn.lili.modules.payment.kit.Payment;
import cn.lili.modules.payment.kit.dto.PayParam;
import cn.lili.modules.payment.kit.dto.PaymentSuccessParams;
import cn.lili.modules.payment.kit.params.dto.CashierParam;
import cn.lili.modules.payment.service.PaymentService;
import cn.lili.modules.payment.service.RefundLogService;
import cn.lili.modules.permission.entity.dos.Role;
import cn.lili.modules.permission.mapper.RoleMapper;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.vos.StoreDetailVO;
import cn.lili.modules.store.mapper.StoreDetailMapper;
import cn.lili.modules.store.mapper.StoreMapper;
import cn.lili.modules.wallet.entity.dos.Recharge;
import cn.lili.modules.wallet.entity.dto.MemberWalletUpdateDTO;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.vo.RechargeVO;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.RechargeService;
import cn.lili.modules.whitebar.entity.dos.Commission;
import cn.lili.modules.whitebar.entity.dos.RateSetting;
import cn.lili.modules.whitebar.entity.vo.RateSettingSearchParams;
import cn.lili.modules.whitebar.entity.vo.RateSettingVO;
import cn.lili.modules.whitebar.mapper.CommissionMapper;
import cn.lili.modules.whitebar.mapper.RateSettingMapper;
import cn.lili.modules.whitebar.service.RateSettingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * WalletPlugin
 *
 * @author Chopper
 * @version v1.0
 * 2021-02-20 10:14
 */
@Slf4j
@Component
public class WalletPlugin implements Payment {

    /**
     * 支付日志
     */
    @Autowired
    private PaymentService paymentService;
    /**
     * 退款日志
     */
    @Autowired
    private RefundLogService refundLogService;
    /**
     * 会员余额
     */
    @Autowired
    private MemberWalletService memberWalletService;
    /**
     * 收银台
     */
    @Autowired
    private CashierSupport cashierSupport;

    //费率
    @Autowired
    private RateSettingMapper rateSettingMapper;

    @Autowired
    private EextensionService eextensionService;

    @Autowired
    private CommissionMapper commissionMapper;

    @Autowired
    private PartnerMapper partnerMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private GradeLevelMapper gradeLevelMapper;

    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private StoreDetailMapper storeDetailMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RateSettingService rateSettingService;

    @Autowired
    private RechargeService rechargeService;


    @Override
    public ResultMessage<Object> h5pay(HttpServletRequest request, HttpServletResponse response, PayParam payParam) {

        savePaymentLog(payParam);
        return ResultUtil.success(ResultCode.PAY_SUCCESS);
    }

    @Override
    public ResultMessage<Object> jsApiPay(HttpServletRequest request, PayParam payParam) {
        savePaymentLog(payParam);
        return ResultUtil.success(ResultCode.PAY_SUCCESS);
    }

    @Override
    public ResultMessage<Object> appPay(HttpServletRequest request, PayParam payParam) {
        savePaymentLog(payParam);
        return ResultUtil.success(ResultCode.PAY_SUCCESS);
    }

    @Override
    public ResultMessage<Object> nativePay(HttpServletRequest request, PayParam payParam) {
        if (payParam.getOrderType().equals(CashierEnum.RECHARGE.name())) {
            throw new ServiceException(ResultCode.CAN_NOT_RECHARGE_WALLET);
        }
        savePaymentLog(payParam);
        return ResultUtil.success(ResultCode.PAY_SUCCESS);
    }

    @Override
    public ResultMessage<Object> mpPay(HttpServletRequest request, PayParam payParam) {

        savePaymentLog(payParam);
        return ResultUtil.success(ResultCode.PAY_SUCCESS);
    }

    @Override
    public void cancel(RefundLog refundLog) {

        try {
            Order order = orderService.getBySn(refundLog.getOrderSn());
            memberWalletService.increase(new MemberWalletUpdateDTO(refundLog.getTotalAmount(),
                    refundLog.getMemberId(),
                    "取消[" + refundLog.getOrderSn() + "]订单，退还金额[" + refundLog.getTotalAmount() + "]",
                    DepositServiceTypeEnum.WALLET_REFUND.name(), order.getOwner()));
            refundLog.setIsRefund(true);
            refundLogService.save(refundLog);
        } catch (Exception e) {
            log.error("订单取消错误", e);
        }
    }

    /**
     * 保存支付日志
     *
     * @param payParam 支付参数
     */
    private void savePaymentLog(PayParam payParam) {
        //获取支付收银参数
        CashierParam cashierParam = cashierSupport.cashierParam(payParam);
        this.callBack(payParam, cashierParam);
    }

    @Override
    public void refund(RefundLog refundLog) {
        try {
            Order order = orderService.getBySn(refundLog.getOrderSn());
            memberWalletService.increase(new MemberWalletUpdateDTO(refundLog.getTotalAmount(),
                    refundLog.getMemberId(),
                    "售后[" + refundLog.getAfterSaleNo() + "]审批，退还金额[" + refundLog.getTotalAmount() + "]",
                    DepositServiceTypeEnum.WALLET_REFUND.name(), order.getOwner()));
            refundLog.setIsRefund(true);
            refundLogService.save(refundLog);
        } catch (Exception e) {
            log.error("退款失败", e);
        }
    }


    //计算佣金
    void countRate(CashierParam cashierParam,MemberVO memberVO,Double rate,String orderType,String owner){
        List<String> list = Arrays.asList(cashierParam.getOrderSns().split(","));
        if(CollectionUtils.isNotEmpty(list)){
            for(String sn : list){
                String type = "订单[";
                Double price = 0D;
                if(orderType.equals(CashierEnum.MEMBER.name())){
                    type = "会员年费订单[";
                }else if(orderType.equals(CashierEnum.DUES.name())){
                    type = "合伙人年费订单[";
                }else if(orderType.equals(CashierEnum.SELLER.name())){
                    type = "商家会员年费订单[";
                }
                if(owner.indexOf("STORE") != -1){
                    owner = WalletOwnerEnum.STORE_PROMOTE.name();
                    if(!orderType.equals(CashierEnum.DUES.name())
                            && !orderType.equals(CashierEnum.MEMBER.name())
                            && !orderType.equals(CashierEnum.SELLER.name())) {
                        OrderVO bySn = orderService.getBySn(sn);
                        price = bySn.getGoodsPrice();
                    }else{
                        Recharge recharge = rechargeService.getRecharge(sn);
                        price = recharge.getRechargeMoney();
                    }
                }else if(owner.indexOf("BUYER") != -1){
                    owner = WalletOwnerEnum.BUYER_PROMOTE.name();
                    if(!orderType.equals(CashierEnum.DUES.name())
                            && !orderType.equals(CashierEnum.MEMBER.name())
                            && !orderType.equals(CashierEnum.SELLER.name())) {
                        OrderVO bySn = orderService.getBySn(sn);
                        price = bySn.getFlowPrice();
                    }else{
                        Recharge recharge = rechargeService.getRecharge(sn);
                        price = recharge.getRechargeMoney();
                    }
                }
                //计算佣金
                Double flow = CurrencyUtil.mul(price,rate);
                memberWalletService.increase(new MemberWalletUpdateDTO(
                        flow,
                        memberVO.getId(),
                        type + cashierParam.getOrderSns() + "]产生佣金[" + flow + "]",
                        DepositServiceTypeEnum.WALLET_COMMISSION.name(), owner));
                Commission commission = new Commission();
                commission.setUserId(memberVO.getId());
                commission.setUserName(memberVO.getUsername());
                if(orderType.equals(CashierEnum.MEMBER.name())){
                    commission.setMember(flow);
                }else if(orderType.equals(CashierEnum.DUES.name())){
                    commission.setMember(flow);
                }else if(orderType.equals(CashierEnum.SELLER.name())){
                    commission.setMember(flow);
                }else {
                    commission.setTransactionFlow(flow);
                }
                commission.setTransactionTime(cashierParam.getCreateTime());
                commission.setSerialNumber(cashierParam.getOrderSns());
                commissionMapper.insert(commission);
            };
        }
    }

    //修改合伙人信息
    void updatePartner(String orderType,Double price){

        MemberVO member = memberService.getUserInfos();
        Partner partner = new Partner();
        if(member.getPartnerType() != null){
            QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", UserContext.getCurrentUser().getId());
            queryWrapper.eq("partner_type",member.getPartnerType());
            queryWrapper.eq("partner_state",0);
            queryWrapper.orderByDesc("end_time");
            queryWrapper.last("limit 1");
            partner = partnerMapper.selectOne(queryWrapper);
            //充值前先把原有的合伙人信息禁用
            partnerMapper.updateByMemberId(UserContext.getCurrentUser().getId());
            partner.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
            partner.setPartnerState(0);
            partner.setCreateBy(UserContext.getCurrentUser().getId());
            partner.setCreateTime(new Date());
            partner.setUpdateBy(null);
            partner.setUpdateTime(null);
        }else {
            //获取时间加一年或加一月或加一天
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.YEAR, 1);//增加一年
            partner.setBeginTime(date);
            partner.setEndTime(cal.getTime());
            partner.setMemberId(UserContext.getCurrentUser().getId());
            partner.setPartnerState(0);
        }
        partner.setPartnerType(0);
        List<RateSetting> rateSettingVOS = rateSettingService.list(new QueryWrapper<>());
        if(CollectionUtils.isNotEmpty(rateSettingVOS)){
            for(RateSetting rateSetting : rateSettingVOS){
                if("推广员".equals(rateSetting.getRoleName())) {
                    if (price.compareTo(rateSetting.getPartnerPrice()) == 0) {
                        partner.setPartnerType(3);
                        partner.setRoleId(rateSetting.getRoleId());
                    }
                }else if("天使合伙人".equals(rateSetting.getRoleName())) {
                    if (price.compareTo(rateSetting.getPartnerPrice()) == 0) {
                        partner.setPartnerType(2);
                        partner.setRoleId(rateSetting.getRoleId());
                    }
                    //商家自动成为天使合伙人
                    if(orderType.equals(CashierEnum.SELLER.name())){
                        partner.setPartnerType(2);
                        partner.setRoleId(rateSetting.getRoleId());
                    }
                }
            }
        }
        partnerMapper.insert(partner);
        //添加推广码
        Member member1 = new Member();
        member1.setId(member.getId());
        if(StringUtils.isEmpty(member.getPromotionCode())){
            member1.setPromotionCode(eextensionService.getExtension());
        }
        memberMapper.updateById(member1);

    }


    //修改会员信息
    void updateMember(Double price){

        MemberVO member = memberService.getUserInfos();
        if(member.getGradeId() != null){
            QueryWrapper<GradeLevel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", UserContext.getCurrentUser().getId());
            queryWrapper.eq("grade_id",member.getGradeId());
            queryWrapper.eq("grade_state",0);
            queryWrapper.orderByDesc("end_time");
            queryWrapper.last("limit 1");
            GradeLevel gradeLevel = gradeLevelMapper.selectOne(queryWrapper);
            //充值前先把原有的会员信息禁用
            gradeLevelMapper.updateByMemberId(UserContext.getCurrentUser().getId());
            gradeLevel.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
            gradeLevel.setGradeState(0);
            gradeLevel.setCreateBy(UserContext.getCurrentUser().getId());
            gradeLevel.setCreateTime(new Date());
            gradeLevel.setUpdateBy(null);
            gradeLevel.setUpdateTime(null);
            List<GradeVO> gradeVOS = gradeMapper.selectList(new QueryWrapper<>());
            if(CollectionUtils.isNotEmpty(gradeVOS)){
                for(GradeVO grade : gradeVOS){
                    if (price.compareTo(grade.getMoney()) == 0 ) {
                        gradeLevel.setGradeId(String.valueOf(grade.getId()));
                    }
                }
            }
            gradeLevelMapper.insert(gradeLevel);
        }else {
            GradeLevel gradeLevel = new GradeLevel();
            //获取时间加一年或加一月或加一天
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.YEAR, 1);//增加一年
            gradeLevel.setBeginTime(date);
            gradeLevel.setEndTime(cal.getTime());
            gradeLevel.setMemberId(UserContext.getCurrentUser().getId());
            gradeLevel.setGradeState(0);
            List<GradeVO> gradeVOS = gradeMapper.selectList(new QueryWrapper<>());
            if(CollectionUtils.isNotEmpty(gradeVOS)){
                for(GradeVO grade : gradeVOS){
                    if (price.compareTo(grade.getMoney()) == 0 ) {
                        gradeLevel.setGradeId(String.valueOf(grade.getId()));
                    }
                }
            }
            gradeLevelMapper.insert(gradeLevel);
        }
    }

    //修改商家会员信息
    void updateSeller(Double price){

        MemberVO member = memberService.getUserInfos();
        if(member.getGradeId() != null){
            QueryWrapper<GradeLevel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", UserContext.getCurrentUser().getId());
            queryWrapper.eq("grade_id",member.getGradeId());
            queryWrapper.eq("grade_state",0);
            queryWrapper.orderByDesc("end_time");
            queryWrapper.last("limit 1");
            GradeLevel gradeLevel = gradeLevelMapper.selectOne(queryWrapper);
            //充值前先把原有的会员信息禁用
            gradeLevelMapper.updateByMemberId(UserContext.getCurrentUser().getId());
            gradeLevel.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
            gradeLevel.setGradeState(0);
            gradeLevel.setCreateBy(UserContext.getCurrentUser().getId());
            gradeLevel.setCreateTime(new Date());
            gradeLevel.setUpdateBy(null);
            gradeLevel.setUpdateTime(null);
            GradeVO gradeVOS = gradeMapper.selectOne(new QueryWrapper<GradeVO>().eq("level","9999"));
            if(gradeVOS != null){
                gradeLevel.setGradeId(String.valueOf(gradeVOS.getId()));
            }
            StoreDetailVO storeDetail = storeDetailMapper.getStoreDetailByMemberId(UserContext.getCurrentUser().getId());
            Store store = new Store();
            store.setId(storeDetail.getStoreId());
            store.setMemberCreateTime(gradeLevel.getBeginTime());
            store.setMemberEndTime(gradeLevel.getEndTime());
            storeMapper.updateById(store);
            gradeLevelMapper.insert(gradeLevel);
        }else {
            GradeLevel gradeLevel = new GradeLevel();
            //获取时间加一年或加一月或加一天
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.YEAR, 1);//增加一年
            gradeLevel.setBeginTime(date);
            gradeLevel.setEndTime(cal.getTime());
            gradeLevel.setMemberId(UserContext.getCurrentUser().getId());
            gradeLevel.setGradeState(0);
            gradeLevel.setCreateBy(UserContext.getCurrentUser().getId());
            gradeLevel.setCreateTime(new Date());
            GradeVO gradeVOS = gradeMapper.selectOne(new QueryWrapper<GradeVO>().eq("level","9999"));
            if(gradeVOS != null){
                gradeLevel.setGradeId(String.valueOf(gradeVOS.getId()));
            }
            StoreDetailVO storeDetail = storeDetailMapper.getStoreDetailByMemberId(UserContext.getCurrentUser().getId());
            Store store = new Store();
            store.setId(storeDetail.getStoreId());
            store.setMemberCreateTime(date);
            store.setMemberEndTime(cal.getTime());
            storeMapper.updateById(store);
            gradeLevelMapper.insert(gradeLevel);
        }
    }


    /**
     * 支付订单
     *
     * @param payParam     支付参数
     * @param cashierParam 收银台参数
     */
    public void callBack(PayParam payParam, CashierParam cashierParam) {

        //支付信息
        try {
            if (UserContext.getCurrentUser() == null) {
                throw new ServiceException(ResultCode.USER_NOT_LOGIN);
            }
            Double price = cashierParam.getPrice();
            if(!payParam.getOrderType().equals(CashierEnum.DUES.name())
                    && !payParam.getOrderType().equals(CashierEnum.MEMBER.name())
                    && !payParam.getOrderType().equals(CashierEnum.SELLER.name())) {
                price = cashierParam.getMemberPrice();
            }
            String type = "订单[";
            if(payParam.getOrderType().equals(CashierEnum.MEMBER.name())){
                type = "会员年费订单[";
            }else if(payParam.getOrderType().equals(CashierEnum.DUES.name())){
                type = "合伙人年费订单[";
            }else if(payParam.getOrderType().equals(CashierEnum.SELLER.name())){
                type = "商家会员年费订单[";
            }
            //买家扣钱
            boolean result = memberWalletService.reduce(new MemberWalletUpdateDTO(
                            price,
                            UserContext.getCurrentUser().getId(),
                            type + cashierParam.getOrderSns() + "]支付金额[" + price + "]",
                            DepositServiceTypeEnum.WALLET_PAY.name(), payParam.getOwner()));
            if (result) {
                if(payParam.getOrderType().equals(CashierEnum.ORDER.name()) ||
                        payParam.getOrderType().equals(CashierEnum.TRADE.name()) ){
                    List<String> list = Arrays.asList(cashierParam.getOrderSns().split(","));
                    if(CollectionUtils.isNotEmpty(list)){
                        list.forEach(sn ->{
                            //卖家加钱--冻结
                            OrderVO bySn = orderService.getBySn(sn);
                            Double sPrice = bySn.getFlowPrice();
                            if(payParam.getOwner().indexOf("STORE") != -1){
                                sPrice = bySn.getGoodsPrice();
                            }else if(payParam.getOwner().indexOf("BUYER") != -1){
                                sPrice = bySn.getFlowPrice();
                            }
                            memberWalletService.inFrozen(new MemberWalletUpdateDTO(
                                    sPrice,
                                    bySn.getSMemberId(),
                                    "订单[" + cashierParam.getOrderSns() + "]冻结订单金额[" + bySn.getFlowPrice() + "]",
                                    DepositServiceTypeEnum.WALLET_PAY.name(), WalletOwnerEnum.STORE_SALE.name()));
                        });
                    }
                }
                //获取推广人
                MemberVO memberVO = eextensionService.findByMemberId(UserContext.getCurrentUser().getId());
                if(memberVO != null){
                    //获取佣金费率
                    RateSettingVO rateSettingVO = rateSettingMapper.findByPartner(memberVO.getId());
                    if(payParam.getOrderType().equals(CashierEnum.DUES.name())){
                        //合伙人佣金
//                        if(rateSettingVO != null && rateSettingVO.getPartnerRate()>0){
//                            countRate(cashierParam,memberVO,rateSettingVO.getPartnerRate(),payParam.getOrderType(), payParam.getOwner());
//                        }
                        //修改合伙人信息
                        updatePartner(payParam.getOrderType(),price);
                    }else if(payParam.getOrderType().equals(CashierEnum.MEMBER.name())) {
                        //充值会员佣金
                        if(rateSettingVO != null && rateSettingVO.getMembershipRate()>0){
                            countRate(cashierParam,memberVO,rateSettingVO.getMembershipRate(),payParam.getOrderType(), payParam.getOwner());
                        }

                        //计算暂存佣金
                        if(StringUtils.isEmpty(memberVO.getPartnerName())){
                            //推广人身份过期
                            Member member = new Member();
                            member.setId( UserContext.getCurrentUser().getId());
                            member.setCommission(CurrencyUtil.mul(price,Double.valueOf("0.5")));
                            memberService.updateById(member);
                        }else if("推广员".equals(memberVO.getPartnerName())){
                            Member member = new Member();
                            member.setId( UserContext.getCurrentUser().getId());
                            member.setCommission(CurrencyUtil.mul(price,Double.valueOf("0.3")));
                            memberService.updateById(member);
                        }
                        //修改会员信息
                        updateMember(price);
                    }else if(payParam.getOrderType().equals(CashierEnum.SELLER.name())) {
                        //充值商家会员佣金
//                        if(rateSettingVO != null && rateSettingVO.getMembershipRate()>0){
//                            countRate(cashierParam,memberVO,rateSettingVO.getMembershipRate(),payParam.getOrderType(), payParam.getOwner());
//                        }
                        //修改会员信息
                        updateSeller(price);
                        //自动成为合伙人
                        updatePartner(payParam.getOrderType(),price);
                    }else{
                        //不是会员时，不计算佣金
                        MemberVO member = memberService.getUserInfos();
                        //消费
                        if(rateSettingVO != null && rateSettingVO.getFlowRate()>0
                                && StringUtils.isNotEmpty(member.getGradeName()) && !"0".equals(member.getGradeName())){
                            countRate(cashierParam,memberVO,rateSettingVO.getFlowRate(),payParam.getOrderType(), payParam.getOwner());
                        }

                    }
                }else{
                    //没有邀请人，不计算佣金
                    //修改合伙人信息
                    if(payParam.getOrderType().equals(CashierEnum.DUES.name())){
                        //修改合伙人信息
                        updatePartner(payParam.getOrderType(),price);
                    }else if(payParam.getOrderType().equals(CashierEnum.MEMBER.name())) {
                        //修改会员信息
                        updateMember(price);
                        //没有推广人，算暂存佣金
                        Member member = new Member();
                        member.setId( UserContext.getCurrentUser().getId());
                        member.setCommission(CurrencyUtil.mul(price,Double.valueOf("0.5")));
                        memberService.updateById(member);
                    }else if(payParam.getOrderType().equals(CashierEnum.SELLER.name())) {
                        //修改会员信息
                        updateSeller(price);
                        //自动成为合伙人
                        updatePartner(payParam.getOrderType(),price);
                    }else{
                        //消费
                    }

                }
                try {
                    PaymentSuccessParams paymentSuccessParams = new PaymentSuccessParams(
                            PaymentMethodEnum.WALLET.name(),
                            "",
                            price,
                            payParam
                    );

                    paymentService.success(paymentSuccessParams);
                    log.info("支付回调通知：余额支付：{}", payParam);
                } catch (ServiceException e) {
                    //业务异常，则支付手动回滚
                    memberWalletService.increase(new MemberWalletUpdateDTO(
                            price,
                            UserContext.getCurrentUser().getId(),
                            "订单[" + cashierParam.getOrderSns() + "]支付异常，余额返还[" + price + "]",
                            DepositServiceTypeEnum.WALLET_REFUND.name(), payParam.getOwner()));
                    throw e;
                }
            } else {
                throw new ServiceException(ResultCode.WALLET_INSUFFICIENT);
            }
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.info("余额支付异常", e);
            throw new ServiceException(ResultCode.WALLET_INSUFFICIENT);
        }

    }

}
